

<template>
    <div class="sdy-search-history">
    <div  class="history box" v-if="historyList.length">
      <div class="title">
        <span>最近搜索</span>
        <van-icon  @click="clearHistoryHandler" class="del" name="delete-o" />
      </div>
      <ul class="content">
        <li
          v-for="item in historyList"
          :key="item"
          @click="clickHandler">{{ item }}</li>
      </ul>
    </div>
    <div class="hot box">
      <div class="title">
        <span >热门搜索</span>
        <span @click="isshow=!isshow">{{isshow ? '隐藏' : '搜索'}}</span>
      </div>
      <!-- 通过添加isshow来控制热门搜索的显示隐藏 -->
      <ul v-if="isshow" class="content">
        <li
          v-for="item in hotList"
          :key="item.wordid"
          @click="clickHandler"
          >
          {{ item.keyword }}
        </li>
      </ul>
      <div v-else class="hid">
       不给你看
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted} from 'vue'
import { useRouter,type Router } from 'vue-router';
import type {MyHotSearchItem} from '@/config/inter'
import { hotSearchApi } from '@/api/goods'

const isshow = ref<boolean>(true)
const $router = useRouter()


// 需要一个数组保存历史记录
const historyList = ref(JSON.parse(window.localStorage.getItem('history') as string) || [])


// 按钮点击跳转页面
const clickHandler=(e:Event)=>{
    const text = (e.target as HTMLElement).innerHTML
    // console.log(text)
    // 跳转到商品页 携带Text去商品列表页
    // 传递这个点击的信息是为了让商品列表页接收点的什么内容从而添加到历史记录
    // 传过来用执行useRouter router.push  query方式 
    // 接收用执行useRoute route 方式
    $router.push({path:'/goodslist',query:{search:text}})
}

// 点击历史记录边上的删除按钮
const clearHistoryHandler = () => {
  // 删除 lcoalStorage 内的 history 一项
  window.localStorage.removeItem('history')
  historyList.value = []
}



// 热门搜索相关
// 准备一个变量保存热门搜索列表
const hotList = ref<MyHotSearchItem[]>([])

// 挂载完毕后请求数据
onMounted(async () => {
  const res = await hotSearchApi()
  hotList.value = res.data
})

</script>

<style scoped lang="scss">
.sdy-search-history {
  height: 100%;
  box-sizing: border-box;
  padding: 15px;

  > .box {
    margin-bottom: 30px;

    > .title {
      display: flex;
      justify-content: space-between;

      .del {
        font-size: 20px;
      }
    }

    > ul {
      display: flex;
      flex-wrap: wrap;
      margin-top: 5px;

      > li {
        background-color: #c4c4c4;
        color: #fff;
        padding: 2px 3px;
        margin: 0 2px;
      }
    }

    > .hid {
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
